package com.ds.robot.assistant.service.impl;

import com.ds.robot.assistant.service.HolidayService;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 作用：
 * 1.http://tool.bitefu.net/jiari/
 * 2.https://api.jiejiariapi.com/v1/holidays/2024
 *
 * @author WeiShaoying
 * 
 */
@Service("holidayBiteService")
@Slf4j
@NoArgsConstructor
public class HolidayBiteServiceImpl implements HolidayService {

    private static final String HOLIDAY_API_URL = "https://tool.bitefu.net/jiari/?d={date}";

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 判断某个日期是否为节假日
     * API: 检查具体日期是否为节假日，工作日对应结果为 0, 休息日对应结果为 1, 节假日对应的结果为 2；
     *
     * @param date
     */
    public boolean isHoliday(String date) {
        String url = HOLIDAY_API_URL.replace("{date}", date);
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            String body = response.getBody();
            return "2".equalsIgnoreCase(body);
        } else {
            log.error("请求节假日API失败，状态码：{}", response.getStatusCode());
            throw new RuntimeException("请求节假日API失败，状态码: " + response.getStatusCode());
        }
    }


    /**
     * 判断某个日期是否为工作日
     *
     * @param date
     */
    public boolean isWorkDay(String date) {
        String url = HOLIDAY_API_URL.replace("{date}", date);
        log.info("请求节假日API: {}", url);
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            String body = response.getBody();
            return "0".equalsIgnoreCase(body);
        } else {
            log.error("请求工作日API失败，状态码：{}", response.getStatusCode());
            throw new RuntimeException("请求工作日API失败，状态码: " + response.getStatusCode());
        }
    }

    /**
     * 判断某个日期是否为休息日，包括节假日和周末
     *
     * @param date
     * @return
     */
    public boolean isRestDay(String date) {
        boolean b = !isWorkDay(date);
        log.info("{} isRestDay: {}", date, b);
        return b;
    }


}
